use lettre::{Message, SmtpTransport, Transport};
use lettre::transport::smtp::authentication::Credentials;
use crate::config::Config;
use tracing::{error, info};

/// 邮件服务
pub struct EmailService {
    smtp_client: SmtpTransport,
    from: String,
}

impl EmailService {
    /// 创建邮件服务实例
    pub fn new(config: &Config) -> Self {
        let creds = Credentials::new(
            config.smtp.username.clone(),
            config.smtp.password.clone(),
        );

        let smtp_client = SmtpTransport::relay(&config.smtp.server)
            .unwrap()
            .credentials(creds)
            .build();

        Self {
            smtp_client,
            from: config.smtp.from.clone(),
        }
    }

    /// 发送验证邮件
    pub async fn send_verification_email(
        &self,
        to: &str,
        token: &str,
    ) -> Result<(), anyhow::Error> {
        let email = Message::builder()
            .from(self.from.parse()?)
            .to(to.parse()?)
            .subject("请验证您的邮箱")
            .body(format!(
                "请点击以下链接验证邮箱: {}/verify-email/{}",
                "https://yourdomain.com", token
            ))?;

        match self.smtp_client.send(&email) {
            Ok(_) => {
                info!("验证邮件已发送至: {}", to);
                Ok(())
            }
            Err(e) => {
                error!("发送验证邮件失败: {:?}", e);
                Err(anyhow::anyhow!("发送邮件失败"))
            }
        }
    }
}